package com.lagou.common.rpc;

import com.lagou.common.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ServerStub {
    NioEventLoopGroup bossGroup ;
    NioEventLoopGroup workGroup;
    ServerBootstrap serverBootstrap;
    String host;
    int port;
    public ServerStub(String host, int port){
        this.bossGroup = new NioEventLoopGroup();
        this.workGroup =  new NioEventLoopGroup();
        this.host = host;
        this.port = port;
        this.serverBootstrap = new ServerBootstrap();
    }

    public void start() throws InterruptedException {
        this.serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new JsonEncoder());
                        pipeline.addLast(new JsonDecoder());
                        pipeline.addLast(new ServerHandler());
                    }
                });
        serverBootstrap.bind(host, port).sync();
    }
}

